﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace SPContrib.Extensions
{
    /// <summary>
    /// Extensions for the IEnumerable class
    /// </summary>
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// Executes the deferred execution of a LINQ query. The result is passed in the out parameter. 
        /// A boolean indicates if the query was successful or not.
        /// </summary>
        public static bool Execute<T>(this IEnumerable<T> instance, out T result)
        {
            result = instance.FirstOrDefault();
            return Equals(result, default(T)) == false;
        }

        /// <summary>
        /// Executes the deferred execution of a LINQ query. The result is passed in the out parameter. 
        /// A boolean indicates if the query was successful or not.
        /// </summary>
        public static bool Execute<T>(this IEnumerable<T> instance, out IEnumerable<T> results)
        {
            results = new List<T>(instance.DefaultIfEmpty());
            return Equals(results.First(), default(T)) == false;
        }

        /// <summary>
        /// Performs the specified action on each element in the collection
        /// </summary>
        /// <param name="action">the code (delegate) to perform on each item</param>
        public static void ForEach<T>(this IEnumerable<T> instance, Action<T> action)
        {
            foreach (T item in instance)
            {
                action(item);
            }
        }
    }
}
